package com.example.word.adapter;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.dict.R;
import com.example.word.bean.Browse;
import com.example.word.bean.Dict;
import com.example.word.bean.StudyPlan;
import com.example.word.bean.Word;
import com.example.word.util.CommonUtils;
import com.example.word.util.HttpUtils;
import com.example.word.util.MessageUtils;
import com.example.word.util.SPUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 词汇适配器
 */

public class DictAdapter extends RecyclerView.Adapter<DictAdapter.ViewHolder> {
    private List<Dict> list = new ArrayList<>();
    private Context mActivity;
    private ItemListener mItemListener;
    private LinearLayout llEmpty;
    private RecyclerView recyclerView;

    public void setItemListener(ItemListener itemListener) {
        this.mItemListener = itemListener;
    }

    public DictAdapter(LinearLayout llEmpty, RecyclerView recyclerView) {
        this.llEmpty = llEmpty;
        this.recyclerView = recyclerView;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        mActivity = viewGroup.getContext();
        View view = LayoutInflater.from(mActivity).inflate(R.layout.item_rv_dict_list, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        Dict dict = list.get(i);
        if (dict != null) {
            String account = (String) SPUtils.get(mActivity, SPUtils.ACCOUNT, "");
            viewHolder.title.setText(dict.getDict());
            viewHolder.content.setText(String.format("%s", dict.getContent() + " (词汇量 " + dict.getWordNumber() + ")"));

            // 查询当前词汇单词学习了多少个
            Map<String, String> requestParam = new HashMap<>();
            requestParam.put("dict", dict.getDict());
            // 调用 API 客户端的方法
            HttpUtils.sendGetRequest("/getUserStudyPlan", requestParam, mActivity, StudyPlan.class, response -> {
                // 加载当前用户学习情况 dayTask,todayCount,totalCount, currentUserDict;
                StudyPlan studyPlan = response.getData();
                viewHolder.studyCount.setText(String.format("%s / %s", studyPlan.getDictStudyCount(), dict.getWordNumber()));
            });

            Glide.with(mActivity)
                    .asBitmap()
                    .load(HttpUtils.downloadUrl + dict.getImg())
                    .error(R.drawable.ic_error)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(viewHolder.img);
            Boolean isAdmin = (Boolean) SPUtils.get(mActivity, SPUtils.IS_ADMIN, false);
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mItemListener != null) {
                        mItemListener.ItemClick(dict);
                    }
                }
            });
            if (isAdmin) {
                viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);
                        dialog.setIcon(R.drawable.a1);//设置图标
                        dialog.setTitle("球球单词");//设置对话框的标题
                        dialog.setMessage("确认要删除【" + dict.getDict() + "】吗? (将清除该词汇所有单词信息)");
                        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Map<String, String> requestParam = new HashMap<>();
                                requestParam.put("dict", dict.getDict());
                                // 调用 API 客户端的方法
                                HttpUtils.sendGetRequest("/deleteDict", requestParam, mActivity, Dict.class, response -> {
                                    list.remove(dict);
                                    notifyDataSetChanged();
                                    Toast.makeText(mActivity, "删除成功", Toast.LENGTH_LONG).show();
                                    if (list != null && list.size() > 0) {
                                        recyclerView.setVisibility(View.VISIBLE);
                                        llEmpty.setVisibility(View.GONE);
                                    } else {
                                        recyclerView.setVisibility(View.GONE);
                                        llEmpty.setVisibility(View.VISIBLE);
                                    }
                                });
                            }
                        });
                        dialog.setNeutralButton("取消", (dialog1, which) -> dialog1.dismiss());
                        dialog.show();
                        return false;
                    }
                });
            }
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void addItem(List<Dict> listAdd) {
        //如果是加载第一页，需要先清空数据列表
        this.list.clear();
        if (listAdd != null) {
            //添加数据
            this.list.addAll(listAdd);
        }
        //通知RecyclerView进行改变--整体
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView title;
        private TextView content;
        private TextView studyCount;

        private ImageView img;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            content = itemView.findViewById(R.id.content);
            studyCount = itemView.findViewById(R.id.studyCount);
            img = itemView.findViewById(R.id.img);
        }
    }

    public interface ItemListener {
        void ItemClick(Dict dict);
    }
}
